package com.csun.cmny.provider.utils.tfpt;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.csun.cmny.util.DateUtil;
import com.xiaoleilu.hutool.util.NumberUtil;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.io.IOUtils;
import org.apache.poi.util.StringUtil;
import org.springframework.util.StringUtils;
import sun.net.www.protocol.http.HttpURLConnection;

import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStreamWriter;
import java.net.URL;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.HashMap;
import java.util.Map;
import java.util.Random;
import java.util.stream.DoubleStream;

//import java.security.MessageDigest;
//import com.core.common.MD5Util;
//import com.core.common.utils.CoreUtils;
//import net.sf.json.JSONObject;

class MD5Util {
    public static String GetMD5Code(String plainText) {

//        byte[] secretBytes = null;
//        try {
//            secretBytes = MessageDigest.getInstance("md5").digest(
//                    plainText.getBytes());
//        } catch (NoSuchAlgorithmException e) {
//            throw new RuntimeException("没有这个md5算法！");
//        }
//        String md5code = new BigInteger(1, secretBytes).toString(16);
//        for (int i = 0; i < 32 - md5code.length(); i++) {
//            md5code = "0" + md5code;
//        }
//        return md5code;
        return Md5Utils.hash(plainText);
    }
}

class CoreUtils {
    public static String getTimeStr(Date d, int n) {
        SimpleDateFormat df = new SimpleDateFormat("YYYYMMddHHmmss");
        return df.format(d);
    }
}

@Slf4j
public class YuanTongUtils {
    public static String KEY = "wbxxxok924zuh8d2711mjkagry6w20m9";
    public static String account = "qkqshouhujia";
    public static String password = "n7zc4auxrp1qh9djidysyc33v2q3lvso";
    public static String passwdEncrypted = getPasswdEncrypted();
    public static String url = "http://api2.ytone.com.cn/";
    public static String test_url = "http://testapi.ytone.com.cn/";


    public static String login_url = url + "api/ytone.ashx?cmd=10000";
    public static String get_user_url = url + "api/ytone.ashx?cmd=20200";
    public static String get_vital_signs_data_url = url + "device/life/hx";
    public static String get_emergency_call_handling_url = url + "api/ytone.ashx?cmd=31001"; //"http://api2.ytone.com.cn/api/ytone.ashx?cmd=30002";
    public static String serviceUrl = url + "api/ytone.ashx?cmd=50011";
    public static String serviceStaffUrl = url + "api/ytone.ashx?cmd=50013";
    public static String payUrl = url + "capitalDocking/pay";      //市扣款
    public static String payServiceUrl = url + "api/ytone.ashx?cmd=90001";      //扣款服务
    public static String refundUrl = url + "capitalDocking/refund";

    //http://api2.ytone.com.cn/api/ytone.ashx?cmd=31001
    public static String get_sleep_data_url = "http://api2.ytone.com.cn/device/life/sleep";
    public static String UserList = "http://api2.ytone.com.cn/api/ytone.ashx?cmd=21010";

    public static void main(String[] args) {
        String d = CoreUtils.getTimeStr(new Date(), 2);
        String timespace = d;
        System.out.println(d);

        String ret = login(timespace);
        //登录 7232041140
        System.out.println(ret);
        System.out.println("****************************");
        JSONObject retObj = JSON.parseObject(ret);
        if (("" + retObj.get("code")).equals("1000")) {
            String vcode = retObj.getString("vcode");

            int pageIndex = 1;
            int pageSize = 100;
            // 获取服务商
            String serivce = getSerivce(pageIndex, pageSize, 0, DateUtil.dateToStr1(new Date()), vcode);
            System.out.println("serivce result:" + serivce);
            JSONObject jsonObject = JSONObject.parseObject(serivce);
            JSONArray items = jsonObject.getJSONArray("items");
            for (int i = 0; i < items.size(); i++) {
                JSONObject object = items.getJSONObject(i);
                String name = object.getString("name");
                if (name.equals("武胜食堂")) {
                    System.out.println("serivce id:" + object.getIntValue("id"));
                }
            }
//
            // 获取服务商员工
            String serviceStaff = getServiceStaff(pageIndex, pageSize, 839725, DateUtil.dateToStr1(new Date()), vcode);
            System.out.println("serviceStaff result:" + serviceStaff);
//
//            JSONObject jsonObject = JSONObject.parseObject(serviceStaff);
//            JSONArray items = (JSONArray) jsonObject.get("items");
//            JSONObject o = (JSONObject)items.get(0);
//            int id = (int) o.get("id");
//
//            String pay = pay(DateUtil.getDateStr(new Date()), 839001, "420104192511160822", DateUtil.getDateStr(new Date()), vcode, 0);
//            System.out.println("pay:" + pay);

            // 获取用户信息
//            String userId = getUser(DateUtil.dateToStr1(new Date()), vcode, "", 0, "", "420105193710181221");
//            System.out.println("userId:" + userId);
//
//            String payService = payService(DateUtil.dateToStr1(new Date()), 839725, DateUtil.dateToStr1(new Date()), vcode, 15281, DateUtil.dateToStr1(new Date()), userId);
//            System.out.println("payService:" + payService);

//            String refund = refund("7306626", DateUtil.getDateStr(new Date()), vcode, "退款退款退款");
//            System.out.println("refund:" + refund);

//            pay(DateUtil.nowDateStr(),);

//            String devCode = "1fcc5a19"; //"1fcc5a19";
//            String fromDate = "2021-07-01";
//            String toDate = "2021-09-26";
//            //System.out.println(UserList);
//            //String userList = getUserList(UserList, fromDate, toDate, pageIndex, pageSize, timespace, vcode);
//            System.out.println(UserList);
//            //生命体征
//            //ret = getVitalSignsData(get_vital_signs_data_url, devCode, fromDate, toDate, pageIndex, pageSize, timespace, vcode);
//            //System.out.println(ret);
//
//            //System.out.println("@@@@@@@@@@@@@@@@@@@@@@@@@@@@@");
//
//
////            devCode = "";
//            //睡眠
//            //ret = getSleepData(get_sleep_data_url, devCode, fromDate, toDate, pageIndex, pageSize, timespace, vcode);
//            //System.out.println(ret);
//
//            //System.out.println("$$$$$$$$$$$$$$$$$$$$$$$$$$$$$");
//
//            int orderType = 1;
//            int isValid = 0;
//            pageIndex = 1;
//            pageSize = 20;
//
//            JSONArray jsonArray = new JSONArray();
//            JSONObject jectcallNumber = new JSONObject();
//            JSONObject jectcallTimeFrom = new JSONObject();
//            JSONObject jectcallTimeEnd = new JSONObject();
//            jectcallNumber.put("coperator", 1);
//            jectcallNumber.put("field", "identity_card_number");
//            jectcallNumber.put("cvalue", "33010219381022091X");
//            jectcallTimeFrom.put("coperator", 4);
//            jectcallTimeFrom.put("field", "call_time");
//            jectcallTimeFrom.put("cvalue", "2021-10-10");
//           /* jectcallTimeEnd.put("coperator", 5);
//            jectcallTimeEnd.put("field", "call_time");
//            jectcallTimeEnd.put("cvalue", "2021-9-24");*/
//            jsonArray.add(jectcallNumber);
//            /*jsonArray.add(jectcallTimeFrom);
//            jsonArray.add(jectcallTimeEnd);*/
//            System.out.println(jsonArray);
//            //应急处理
//            ret = getEmergencyCallHandling(get_emergency_call_handling_url, isValid, orderType, pageIndex, pageSize, jsonArray, timespace, vcode);
//            System.out.println(ret);
//            //System.out.println(ret);
//            //System.out.println("################################");
//            //System.out.println(ret);
//            //System.out.println("?????????????????");

        }


//        String signature = MD5Util
//                .GetMD5Code(account +password+timespace+tracknumber+KEY);
/*
        String signature = MD5Util
                .GetMD5Code(account +password+timespace+KEY);
        System.out.println(signature);
        Map<String, Object> params = new HashMap<String, Object>();
//        params.put("tracknumber", tracknumber);
        params.put("account", account);
        params.put("password", password);

        params.put("signature", signature);
        params.put("timespace", timespace);
        params.put("vcode", "");
//        JSONObject obj=JSONObject.fromObject(params);
        JSONObject obj=new JSONObject(params);
        System.out.println(obj.toString());
        //System.out.println(YuanTongUtils.postGPS(obj.toString()));
//        System.out.println(YuanTongUtils.postGPS2(obj.toString()));
*/

    }

    public static String getPasswdEncrypted() {
        try {
            String encodedPasswd = java.net.URLEncoder.encode(password, "UTF-8");
            byte[] encrypted = DescTest.encrypt(encodedPasswd, KEY.substring(0, 8));
            String hexStr = DescTest.toHexString(encrypted);
            return hexStr;
        } catch (Exception e) {
            System.out.println(e);
        }
        return null;
    }

    public static String login(String timespase) {
        String signature = MD5Util.GetMD5Code(account + password + timespase + KEY);
        JSONObject jsObj = new JSONObject();
        jsObj.put("signature", signature);
        jsObj.put("timespace", timespase);
        jsObj.put("vcode", "");
        jsObj.put("account", account);
        jsObj.put("password", passwdEncrypted);
        String ret = post(login_url, jsObj.toJSONString());
        return ret;
    }

    // 获取用户信息
    public static String   getUser(String timespace, String vcode, String phone, int userId, String deviceCode, String userCard) {
        String signature = Md5Utils.hash(account + phone + timespace + vcode + KEY);
        JSONObject jsObj = new JSONObject();
        jsObj.put("signature", signature);
        jsObj.put("timespace", timespace);
        jsObj.put("vcode", vcode);
        jsObj.put("account", account);
        jsObj.put("user_card", userCard);
        if ("".compareTo(phone) < 0) {
            jsObj.put("call_phone", phone);
        }
        if (userId > 0) {
            jsObj.put("user_id", userId);
        }
        if ("".compareTo(deviceCode) < 0) {
            jsObj.put("device_code", deviceCode);
        }
        log.info("getUser param:" + jsObj.toJSONString());
        String ret = post(get_user_url, jsObj.toJSONString());

        JSONObject users = JSONObject.parseObject(ret).getJSONObject("users");
        log.info("getUser result:" + jsObj.toJSONString());
        String id = users.getString("id");
        return id;
    }

    public static String getVitalSignsData(String sUrl, String devCode, String fromDate, String toDate, int pageIndex, int pageSize, String timespace, String vcode) {
        String signature = Md5Utils.hash(account + fromDate + toDate + pageIndex + timespace + vcode + KEY);
        JSONObject jsObj = new JSONObject();
        jsObj.put("signature", signature);
        jsObj.put("timespace", timespace);
        jsObj.put("vcode", vcode);
        jsObj.put("account", account);
        jsObj.put("devcode", devCode);
        jsObj.put("fromDate", fromDate);
        jsObj.put("toDate", toDate);
        jsObj.put("pageIndex", pageIndex);
        jsObj.put("pageSize", pageSize);
        String ret = post(get_vital_signs_data_url, jsObj.toJSONString());
        return ret;
    }

    public static String getSerivce(int pageidx, int pagesize, Integer seller_id, String timespace, String vcode) {
        String signature = Md5Utils.hash(account + pageidx + pagesize + seller_id + timespace + vcode + KEY);
        JSONObject jsObj = new JSONObject();
        jsObj.put("signature", signature);
        jsObj.put("timespace", timespace);
        jsObj.put("vcode", vcode);
        jsObj.put("account", account);
        jsObj.put("pageidx", pageidx);
        jsObj.put("pagesize", pagesize);
        jsObj.put("seller_id", seller_id);
        jsObj.put("service_type1", "养老服务");

        System.out.println(jsObj.toJSONString());
        String ret = post(serviceUrl, jsObj.toJSONString());
        return ret;
    }

    public static String getServiceStaff(int pageidx, int pagesize, Integer seller_id, String timespace, String vcode) {
        String signature = Md5Utils.hash(account + pageidx + pagesize + seller_id + timespace + vcode + KEY);
        JSONObject jsObj = new JSONObject();
        jsObj.put("signature", signature);
        jsObj.put("timespace", timespace);
        jsObj.put("vcode", vcode);
        jsObj.put("account", account);
        jsObj.put("pageidx", pageidx);
        jsObj.put("pagesize", pagesize);
        jsObj.put("seller_id", seller_id);

        System.out.println(jsObj.toJSONString());
        String ret = post(serviceStaffUrl, jsObj.toJSONString());
        return ret;
    }

    public static String pay(String dedu_time, int facilitator_id, String idcard, String timespace, String vcode, int facilitator_staff_id) {
        String signature = Md5Utils.hash(account + dedu_time + facilitator_id + idcard + timespace + vcode + KEY);
        JSONObject jsObj = new JSONObject();
        jsObj.put("signature", signature);
        jsObj.put("timespace", timespace);
        jsObj.put("vcode", vcode);
        jsObj.put("account", account);
        jsObj.put("idcard", idcard);
        jsObj.put("dedu_time", dedu_time);
        jsObj.put("facilitator_id", facilitator_id);
        jsObj.put("facilitator_staff_id", facilitator_staff_id);
        jsObj.put("service_content", "服务支付调用");

        JSONArray jsonArray = new JSONArray();
        JSONObject jsonObject = new JSONObject();
        jsonObject.put("num", 1);
        jsonObject.put("price", 25);
        jsonObject.put("server_name", "按摩");
        jsonObject.put("unit", "元");
        jsonArray.add(jsonObject);
        jsObj.put("service_items", jsonArray);

        log.info(jsObj.toJSONString());
        String ret = post(payUrl, jsObj.toJSONString());
        return ret;
    }

    // 扣款服务
    public static String payService(String dedu_time, int facilitator_id, String timespace, String vcode, int facilitator_staff_id,
                                    String service_s_time, String userId, String server_name,String server_content,int price) {
        String signature = Md5Utils.hash(account + dedu_time + facilitator_id + userId + timespace + vcode + KEY);
        JSONObject jsObj = new JSONObject();
        jsObj.put("signature", signature);
        jsObj.put("timespace", timespace);
        jsObj.put("vcode", vcode);
        jsObj.put("account", account);
        jsObj.put("dedu_time", dedu_time);
        jsObj.put("facilitator_id", facilitator_id);
        jsObj.put("facilitator_staff_id", facilitator_staff_id);
        jsObj.put("service_content", server_name);

        // userid,cash,coupon,service_s_time,service_content,time

        jsObj.put("userid", userId);
        jsObj.put("cash", price);
        jsObj.put("coupon", 0);
        jsObj.put("service_s_time", service_s_time);
        jsObj.put("service_content", StringUtils.isEmpty(server_content) ? "家床其他服务" : server_content);
        jsObj.put("time", 0);

        JSONArray jsonArray = new JSONArray();
        JSONObject jsonObject = new JSONObject();
        jsonObject.put("num", 1);
        jsonObject.put("priace", price);
        jsonObject.put("server_name", StringUtils.isEmpty(server_name) ? "服务" : server_name);
        jsonObject.put("unit", "元");
        jsonArray.add(jsonObject);
        jsObj.put("service_items", jsonArray);

        log.info("扣款服务 param：" + jsObj.toJSONString());
        String ret = post(payServiceUrl, jsObj.toJSONString());
        log.info("扣款服务 resule：" + ret);
        return ret;
    }

    public static String refund(String serial_number, String timespace, String vcode, String reason) {
        String signature = Md5Utils.hash(account + serial_number + timespace + vcode + KEY);
        JSONObject jsObj = new JSONObject();
        jsObj.put("signature", signature);
        jsObj.put("timespace", timespace);
        jsObj.put("vcode", vcode);
        jsObj.put("account", account);
        jsObj.put("serial_number", serial_number);
        jsObj.put("reason", reason);

        System.out.println(jsObj.toJSONString());
        String ret = post(refundUrl, jsObj.toJSONString());
        return ret;
    }

    public static String getEmergencyCallHandling(String sUrl, int isValid, int orderType, int currentPage, int pageSize, JSONArray items, String timespace, String vcode) {
        String signature = Md5Utils.hash(account + pageSize + currentPage + timespace + vcode + KEY);
        JSONObject jsObj = new JSONObject();
        jsObj.put("signature", signature);
        jsObj.put("timespace", timespace);
        jsObj.put("vcode", vcode);
        jsObj.put("account", account);
        jsObj.put("isvalid", isValid);
        jsObj.put("ordertype", orderType);
        jsObj.put("currpage", currentPage);
        jsObj.put("pagesize", pageSize);
        jsObj.put("items", items);

        System.out.println(jsObj.toJSONString());
        String ret = post(sUrl, jsObj.toJSONString());
        return ret;
    }

    public static String getSleepData(String sUrl, String devcode, String fromDate, String toDate, int pageIndex, int pageSize, String timespace, String vcode) {
        String signature = Md5Utils.hash(account + fromDate + toDate + pageIndex + timespace + vcode + KEY);
        JSONObject jsObj = new JSONObject();
        jsObj.put("signature", signature);
        jsObj.put("timespace", timespace);
        jsObj.put("vcode", vcode);
        jsObj.put("account", account);
        jsObj.put("devcode", devcode);
        jsObj.put("fromDate", fromDate);
        jsObj.put("toDate", toDate);
        jsObj.put("pageIndex", pageIndex);
        jsObj.put("pageSize", pageSize);
        System.out.println(jsObj.toJSONString());
        String ret = post(sUrl, jsObj.toJSONString());
        return ret;
    }

    public static String post(String sUrl, String jsonStrParam) {
        try {
            // Configure and open a connection to the site you will send the request
            URL url = new URL(sUrl);
            HttpURLConnection urlConnection = (HttpURLConnection) url.openConnection();
            // 设置doOutput属性为true表示将使用此urlConnection写入数据
            urlConnection.setDoOutput(true);
            // 定义待写入数据的内容类型，我们设置为application/x-www-form-urlencoded类型
            urlConnection.setRequestProperty("content-type", "application/x-www-form-urlencoded");
            // 得到请求的输出流对象
            OutputStreamWriter out = new OutputStreamWriter(urlConnection.getOutputStream());
            // 把数据写入请求的Body
            out.write(jsonStrParam);
            out.flush();
            out.close();
            // 从服务器读取响应
            InputStream inputStream = urlConnection.getInputStream();
            String encoding = urlConnection.getContentEncoding();
            String body = IOUtils.toString(inputStream, encoding);


            if (urlConnection.getResponseCode() == 200) {
//                    JSONObject obj=JSONObject.fromObject(body);
/*
                JSONObject obj= JSON.parseObject(body);
                Integer code=(Integer) obj.get("code");
                String msg=(String) obj.get("msg");
                System.out.println(body);

                map.put("code", code);
                map.put("msg", msg);
                return map;
*/
                return body;
            } else {
//                map.put("code", "-1");
//                map.put("msg", "接口异常");
//                return map;
                String s = "{\"code\": \"-1\", \"msg\":\"接口异常\"}";
                return s;
            }
        } catch (IOException e) {
//            map.put("code", "-1");
//            map.put("msg", "接口异常");
//            return map;
            String s = "{\"code\": \"-1\", \"msg\":\"接口异常\"}";
            return s;
        }
    }


    public static Map<String, String> postGPS(String json) {
        {
            Map map = new HashMap();
            String urls = "http://api.ytone.com.cn/Apply/gps.ashx?cmd=postgps";
            try {
                // Configure and open a connection to the site you will send the request
                URL url = new URL(urls);
                HttpURLConnection urlConnection = (HttpURLConnection) url.openConnection();
                // 设置doOutput属性为true表示将使用此urlConnection写入数据
                urlConnection.setDoOutput(true);
                // 定义待写入数据的内容类型，我们设置为application/x-www-form-urlencoded类型
                urlConnection.setRequestProperty("content-type", "application/x-www-form-urlencoded");
                // 得到请求的输出流对象
                OutputStreamWriter out = new OutputStreamWriter(urlConnection.getOutputStream());
                // 把数据写入请求的Body
                out.write(json);
                out.flush();
                out.close();
                // 从服务器读取响应
                InputStream inputStream = urlConnection.getInputStream();
                String encoding = urlConnection.getContentEncoding();
                String body = IOUtils.toString(inputStream, encoding);


                if (urlConnection.getResponseCode() == 200) {
//                    JSONObject obj=JSONObject.fromObject(body);
                    JSONObject obj = JSON.parseObject(body);
                    Integer code = (Integer) obj.get("code");
                    String msg = (String) obj.get("msg");
                    System.out.println(body);

                    map.put("code", code);
                    map.put("msg", msg);
                    return map;
                } else {
                    map.put("code", "-1");
                    map.put("msg", "接口异常");
                    return map;
                }
            } catch (IOException e) {
                map.put("code", "-1");
                map.put("msg", "接口异常");
                return map;

            }


        }
    }

    public static Map<String, String> postGPS2(String json) {
        {
            Map map = new HashMap();
            String urls = "http://localhost:8080/desktop/wap/location/toLocation";
            try {
                // Configure and open a connection to the site you will send the request
                URL url = new URL(urls);
                HttpURLConnection urlConnection = (HttpURLConnection) url.openConnection();
                // 设置doOutput属性为true表示将使用此urlConnection写入数据
                urlConnection.setDoOutput(true);
                // 定义待写入数据的内容类型，我们设置为application/x-www-form-urlencoded类型
                urlConnection.setRequestProperty("content-type", "text/html;charset=utf-8");
                // 得到请求的输出流对象
                OutputStreamWriter out = new OutputStreamWriter(urlConnection.getOutputStream());
                // 把数据写入请求的Body
                out.write(json);
                out.flush();
                out.close();
                // 从服务器读取响应
                InputStream inputStream = urlConnection.getInputStream();
                String encoding = urlConnection.getContentEncoding();
                String body = IOUtils.toString(inputStream, encoding);

                // System.out.println("body111="+body);
                if (urlConnection.getResponseCode() == 200) {
//                    JSONObject obj=JSONObject.fromObject(body);
                    JSONObject obj = JSON.parseObject(body);
                    Integer code = (Integer) obj.get("code");
                    String msg = (String) obj.get("msg");
                    //System.out.println(body);

                    map.put("code", code);
                    map.put("msg", msg);
                    return map;
                } else {
                    map.put("code", "-1");
                    map.put("msg", "接口异常");
                    return map;
                }
            } catch (IOException e) {
                map.put("code", "-1");
                map.put("msg", "接口异常");
                return map;

            }


        }
    }

    public static String getUserList(String sUrl, String fromDate, String toDate, int pageIndex, int pageSize, String timespace, String vcode) {
        String hash = Md5Utils.hash(account + fromDate + toDate + pageIndex + timespace + vcode + KEY);
        //String hash = Md5Utils.hash("hongai2021-09-122021-09-131202109181439431400843454w4dsxqhglf76r086you5de7kp33bjq4u");
        System.out.println(hash);
        System.out.println(account + fromDate + toDate + pageIndex + timespace + vcode + KEY);
        JSONObject object = new JSONObject();
        object.put("account", account);
        object.put("fromDate", fromDate);
        object.put("toDate", toDate);
        object.put("pageIndex", pageIndex);
        object.put("pageSize", pageSize);
        object.put("timespace", timespace);
        object.put("vcode", vcode);
//        object.put("userNo","");
        object.put("signature", hash);
        //System.out.println(object.toJSONString());
        String post = post(sUrl, object.toJSONString());
        System.out.println(post);
        return post;
    }

    public static Double getRandom() {
        int[] ints = NumberUtil.generateRandomNumber(33, 40, 1);
        int anInt = ints[0];
        String str = "0." + anInt;

        return Double.valueOf(str);
    }


}
